<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/9/11
 * Time: 11:49
 */

namespace app\admin\controller;


use app\admin\model\OrderHead;
use app\common\controller\Excel;
use think\Exception;
use think\Loader;

class Order extends Common
{
    public function index() {
        return $this->fetch("order-list");
    }

    public function getDatas() {
        $limit = $this->request->get('limit');
        $page = $this->request->get('page');
//        $orderField = $this->request->get('field');
//        $orderType = $this->request->get('order');
        $alias = "a";
        $join = [["OrderList b","a.order_no = b.order_no"]];
        $field = "*,b.note as listnote,@i:=@i+1 as autonum";
//        $orderBy = [$orderField => $orderType];
        $orderHead = Loader::model("OrderHead");
        //数据集序号设定
        $i = 0;
        if ($page>1) {
            $i = ($page-1)*$limit;
        }
        $orderHead->query("set @i=".$i);
//        $data = $orderHead->alias($alias)->join($join)->field($field)->page($page,$limit)->order($orderBy)->select();
        $data = $orderHead->alias($alias)->join($join)->field($field)->page($page,$limit)->select();
        $dataCount = $orderHead->alias($alias)->join($join)->count();
        $data_format = [
            "code" => 0,
            "msg" => "success",
            "count" => $dataCount,
            "data" => $data,
        ];
        return $data_format;
    }

    public function exportData() {
            try{
                $datas = $this->request->param("data/a");
                foreach ($datas as $k => $row) {
                    $datas[$k] = json_decode($row,true);
                }
                $excelObj = new Excel();
                $excelObj->exportExcel($datas);
            }catch (\Exception $e) {
                file_put_contents('log.txt',$e->getMessage());
            }
    }

    public function importData() {
        $file = $this->request->file("excelFile");
        $rootpath = 'public' . DS . 'uploads';
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->validate(['ext'=>'xls,xlsx'])->move(ROOT_PATH.$rootpath);
        if($info){
            $excelObj = new Excel();
            // 成功上传后 获取文件路径
//            $filepath ="/excelPlat/".$rootpath.DS.$info->getSaveName();
            $filepath =ROOT_PATH.$rootpath.DS.$info->getSaveName();
            $excelObj->setFilePath($filepath);
            //获得excel表中所有记录
            $datas = $excelObj->getSheetsContent();
            //合并相同订单号的记录并区分
            $datas = $excelObj->getSameOrder($datas,0);
            //定义订单头信息字段,必须按照excel表列的顺序
            $headarr = ["order_no","consignee","consignee_telephone","buyer_id_number","consignee_address","note"];
            //定义订单详细信息字段,必须按照excel表列的顺序,注意因为数组字段要与excel表的列同步，所以listarr的起始下标应紧接headarr之后,且之前的下标要为空
            $listarr = ["item_name","item_no","item_describe","qty","price","currency","note"];
            $listarr = array_merge($headarr,$listarr);
            foreach ($headarr as $k => $val) {
                $listarr[$k] = "";
            }
            //实例化订单头模型，并执行保存数据方法，已包含订单详细信息的存储处理
            $orderHead = Loader::model('OrderHead');
            $result = $orderHead->saveDatas($datas,$headarr,$listarr);
//            unlink($filepath);
            if ($result["code"] == "0000") {
                return json([
                    "code" => "0000",
                    "msg" => $result["msg"],
                    "data" => []
                ]);
            }else{
                return json([
                    "code" => "0001",
                    "error" => $result["error"],
                ]);
            }
        }else{
            // 上传失败获取错误信息
            return json(['error'=>$file->getError()]);
        }
    }
}